#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019, Ethan Slattery
# Copyright (c) 2021, Niklas Hauser
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

import math

def init(module):
    module.name = ":platform:core"
    module.description = FileReader("module.md")

def prepare(module, options):
    if options[":target"].identifier.platform != "sam":
        return False

    module.depends(":platform:cortex-m")
    return True


def build(env):
    target = env[":target"].identifier
    env.substitutions = {"target": target}
    env.outbasepath = "modm/src/modm/platform/core"
    # startup helper code
    env.template("startup_platform.c.in")

    # delay code that must be tuned for each family
    # (cycles per loop, setup cost in loops, max cpu frequency)
    tuning = {
        "d1x/d2x/dax": (3, 4,  48), # CM0 tested on D21 in RAM
        "d5x/e5x":     (4, 4, 120), # CM4 tested on E54 in RAM
        "g5x":         (6, 4, 120), # G55
        "e7x/s7x/v7x": (4, 4, 300), # CM7 tested on V71
    }[target.family]

    # us_shift is an optimization to limit error via fractional math
    us_shift = 32 - math.ceil(math.log2(tuning[2] * 1e6))

    env.substitutions.update({
        "with_cm0": env[":target"].has_driver("core:cortex-m0*"),
        "with_cm7": env[":target"].has_driver("core:cortex-m7*"),
        "loop": tuning[0],
        "shift": int(math.log2(tuning[1])),
        "us_shift": us_shift,
        "with_assert": env.has_module(":architecture:assert")
    })
    env.template("../cortex/delay_ns.cpp.in", "delay_ns.cpp")
    env.template("../cortex/delay_ns.hpp.in", "delay_ns.hpp")
    env.template("../cortex/delay_impl.hpp.in", "delay_impl.hpp")


def post_build(env):
    env.substitutions = env.query("::cortex-m:linkerscript")
    env.substitutions.update(env.query("::cortex-m:vector_table"))
    env.outbasepath = "modm/link"
    env.template("../cortex/ram.ld.in", "linkerscript.ld")
